import React, { Component } from "react";
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  ScrollView,
  ActivityIndicator,
  RefreshControl,
  KeyboardAvoidingView
} from "react-native";
import { wp, hp } from "../../Style/responsive";
import { colors } from "../../Style/Colors";
import DatePicker from "react-native-datepicker";
import { captureVitals, addVitals } from "../../api/config";
import { setVitalDate } from "../../Components/SetDate";
import UserData from "../../Data/UserData";
import Toast from "react-native-simple-toast";

class Vitals extends Component {
  state = {
    list: [],
    date: setVitalDate(new Date()),
    isLoading: true,
    data: [],
    text: [],
    refreshing: false
  };

  componentDidMount = () => {
    this.reRenderSomething = this.props.screenProps.navigation.addListener(
      "willFocus",
      () => {
        this.setState({ isLoading: true });
        captureVitals().then(data => {
          this.setState({ list: data, isLoading: false });
        });
      }
    );
  };

  componentWillUnmount = () => {
    this.reRenderSomething.remove();
  };

  onAdd = () => {
    const isEnterAllData = this.state.list.some(data => {
      if (!this.state[data.Discription]) {
        Toast.show("Enter All Data");
        return true;
      }
    });

    if (!isEnterAllData) {
      this.setState({ isLoading: true });
      this.state.list.map(data => {
        const apiData = {
          PV_ID: data.VM_ID,
          REGNO:
            this.props.screenProps.patientData.RegNo ||
            this.props.screenProps.patientData.REGNO,
          IPD_NO: this.props.screenProps.patientData.IPDNO || 0,
          ADD_DATETIME: setVitalDate(new Date()),
          Description: data.Discription,
          V_Value: this.state[data.Discription],
          userName: UserData.data.UserName,
          VitalDatetime: this.state.date
        };

        setTimeout(() => {
          addVitals(apiData)
            .then(res => {
              if (res === true) {
                this.setState({ isLoading: false });
                Toast.show("Data added: " + data.Discription);
              } else {
                this.setState({ isLoading: false });
                Toast.show("Data is not added");
              }
            })
            .catch(err => {
              this.setState({ isLoading: false });
            });
        }, 1000);
      });
    }
  };

  onTextHandle = (key, value) => {
    this.setState({ [key]: value });
  };

  onRefresh = () => {
    this.setState({ refreshing: true, isLoading: true });
    captureVitals().then(data => {
      this.setState({ list: data, refreshing: false, isLoading: false });
    });
  };

  onSubmit(i) {
    const node = this._nodes.get(i + 1);
    if (node) {
      node.focus();
    }
  }

  render() {
    const { isLoading, list, refreshing } = this.state;
    this._nodes = new Map();

    if (isLoading) {
      return (
        <View style={styles.container}>
          <ActivityIndicator size="large" color={colors.primaryColor} />
        </View>
      );
    } else {
      return (
        <View style={styles.container}>
          <View style={styles.dateWrapper}>
            <Text style={[styles.title, { fontSize: 18 }]}> Select Date</Text>
            <DatePicker
              style={{ width: 160 }}
              date={this.state.date}
              mode="date"
              format="DD-MM-YYYY"
              maxDate={new Date()}
              confirmBtnText="Confirm"
              cancelBtnText="Cancel"
              showIcon={false}
              customStyles={{
                dateInput: {
                  marginLeft: 20,
                  borderWidth: 0.3
                }
              }}
              onDateChange={date => {
                this.setState({ date });
              }}
            />
          </View>
          <KeyboardAvoidingView
            keyboardVerticalOffset={20}
            behavior="position"
            style={{ flex: 1 }}
          >
            <ScrollView
              showsVerticalScrollIndicator={false}
              refreshControl={
                <RefreshControl
                  colors={[colors.primaryColor]}
                  refreshing={refreshing}
                  onRefresh={this.onRefresh}
                />
              }
            >
              {list.map((data, i) => (
                <View key={data.VM_ID} style={styles.contentWrapper}>
                  <Text style={styles.title}>
                    {data.Discription} {data.Unit ? `(${data.Unit})` : ""}
                  </Text>
                  <TextInput
                    returnKeyType="next"
                    keyboardType="number-pad"
                    style={styles.textInput}
                    onChangeText={text =>
                      this.onTextHandle(data.Discription, text)
                    }
                    ref={c => this._nodes.set(i, c)}
                    onSubmitEditing={() => this.onSubmit(i)}
                    blurOnSubmit={false}
                  />
                </View>
              ))}
            </ScrollView>
          </KeyboardAvoidingView>
          <View
            style={{
              flexDirection: "row",
              justifyContent: "center",
              alignItems: "center"
            }}
          >
            <TouchableOpacity
              activeOpacity={0.8}
              onPress={this.onAdd}
              style={styles.buttonWrapper}
            >
              <Text style={styles.buttonText}>Add</Text>
            </TouchableOpacity>
            <TouchableOpacity activeOpacity={0.8} style={styles.buttonWrapper}>
              <Text style={styles.buttonText}>Cancel</Text>
            </TouchableOpacity>
          </View>
        </View>
<<<<<<< HEAD
      );
    }
=======
        <TouchableOpacity activeOpacity={0.8} style={styles.buttonWrapper}>
          <Text style={styles.buttonText}>Add</Text>
        </TouchableOpacity>
      </ScrollView>
    );
>>>>>>> 503b0544130247b48d86f53bc47ed722f01e5c05
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
<<<<<<< HEAD
=======
    padding: 10,
>>>>>>> 503b0544130247b48d86f53bc47ed722f01e5c05
    backgroundColor: colors.offWhite
  },
  contentWrapper: {
    flexDirection: "row",
    alignItems: "center",
    marginHorizontal: 10,
    justifyContent: "space-between",
    borderBottomColor: colors.lightGrey,
    borderBottomWidth: 1
  },
  textInput: {
    borderBottomWidth: 0.6,
    width: wp("16%"),
    marginHorizontal: 10,
    marginBottom: 10,
    borderColor: "#333",
    paddingVertical: 14
  },
  text: {
    fontSize: hp("2.2%"),
    color: "#333"
  },
  buttonWrapper: {
    backgroundColor: colors.primaryColor,
    padding: 10,
    width: wp("40%"),
    margin: 6,
    alignItems: "center"
  },
  buttonText: {
    fontSize: hp("2.4%"),
    color: colors.whiteColor
  },
  title: {
    fontSize: 14,
    marginLeft: 20,
    color: "#333"
  },
  dateWrapper: {
    backgroundColor: "transparent",
    justifyContent: "center",
    alignItems: "center",
    flexDirection: "row"
  }
});

export default Vitals;
